# -*- coding:utf-8 -*-
import tornado.web
from toTest.commons import mod_Sessions
import os
from toTest.commons import mod_Validation
import time


CONT1S = []
CONT2S = []
class UIHandler(tornado.web.RequestHandler):
	def get(self):
		mt_arg = 'foo_mt'
		md_arg = 'foo_md'
		cont1 = self.get_argument('cont1',None)
		if cont1:
			CONT1S.append(cont1)
		cont2 = self.get_argument('cont2',None)
		if cont2:
			CONT2S.append(cont2)
		self.render('foo/ui.html', cont1s=CONT1S, cont2s=CONT2S,mt_arg=mt_arg,md_arg=md_arg)
	# def post(self, *args, **kwargs):
	# 	cont1 = self.get_argument('cont1')
	# 	cont2 = self.get_argument('cont2')
	# 	CONT1S.append(cont1)
	# 	CONT2S.append(cont2)
	# 	self.render('foo/ui.html', cont1s=CONT1S, cont2s=CONT2S,mt_arg=mt_arg,md_arg=md_arg)

class RegHandler(tornado.web.RequestHandler):
	def get(self, nid,num):
		print nid,num
		self.write('{}:{}'.format(nid,num))

class Cookie1Handler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		self.set_cookie('a','aaa')
		ckes = self.cookies
		cke = self.get_cookie('a')
		print ckes,cke
		self.render('foo/cookie1.html')

class Cookie2Handler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		if self.get_argument('user',None) in ['admin','abc']:
			# self.set_cookie('c_user1',self.get_argument('user'))
			self.set_secure_cookie('c_user2',self.get_argument('user'))
			self.redirect('/foo/manager')
		else:
			self.write('请登录')

class ManagerHandler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		# if self.get_cookie('c_user1',None) in ['admin','abc']:
		# print self.get_secure_cookie('c_user2',None)  # 若为Python3x则需转换成str
		if self.get_secure_cookie('c_user2',None) in ['admin','abc']:
			self.write('欢迎登录' + self.get_secure_cookie('c_user2'))
		else:
			self.redirect('/foo/cookie2')

'''
container = {}  # 保存在服务端  # 放于内存/数据库/缓存（另外一台机器的内存）--保正服务器重启不被销毁
class Cookie3Handler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		if self.get_argument('user',None) in ['admin','abc']:
			import hashlib
			import time
			obj = hashlib.md5()
			obj.update(str(time.time()))
			random_str =  obj.hexdigest()
			container[random_str] = {}
			container[random_str]['k1'] = 11111111111
			container[random_str]['k2'] = self.get_argument('user') + 'foo'
			container[random_str]['is_login'] = True    # 可以根据`is_login`判断用户是否已经登录
			# 将random_str保存在客户端
			self.set_cookie('asd',random_str)
			self.redirect('/foo/manager3')
		else:
			self.write('请登录')

class Manager3Handler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		random_str = self.get_cookie('asd')
		current_user_info = container.get(random_str,None)
		if not current_user_info:
			self.redirect('/foo/cookie3')
		else:
			if current_user_info.get('is_login',None):
				temp = '{}-{}'.format(current_user_info.get('k1',''),current_user_info.get('k2',''))
				self.write(temp)
			else:  # 比如超管理改掉'is_login'
				self.redirect('/foo/cookie3')
'''

class BaseHandler(tornado.web.RequestHandler):
	def initialize(self):
		self.obj = mod_Sessions.SessionFactory
		self.session = self.obj.get_session_obj(self)

# container = session.container  # 未定义基类时需创建该对象
class Cookie4Handler(BaseHandler):
	def get(self, *args, **kwargs):
		if self.get_argument('user', None) in ['admin','abc']:
			# self.session.set_value('is_login', True)  # 其它框架`self.session['is_login'] = True`表示设置值，self.session['is_login']表示获取值
			# self.session.set_value('name', self.get_argument('user', None))
			self.session['is_login'] = True
			self.session['name'] = self.get_argument('user', None)
			# print self.session.session_container
			self.redirect('/foo/manager4')
		else:
			self.write('请登录')

class Manager4Handler(BaseHandler):
	def get(self, *args, **kwargs):
		print self.session['is_login']
		print self.session['name']
		print self.session.random_str
		val = self.session['is_login']
		if val:
			self.write('欢迎登录：{}'.format(self.session['name']))
		else:
			self.write('失败')

class CsrfHandler(BaseHandler):
	def get(self, *args, **kwargs):
		self.render('foo/csrf.html')

	def post(self, *args, **kwargs):
		# con1 = self.get_argument('con1')
		# con2 = self.get_argument('con2')
		# con3 = self.get_argument('con3')
		self.write('aaaaaaa')

IMG_LIST = []
class AjaxHandler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		self.render('foo/ajax.html', img_list=IMG_LIST)

	def post(self, *args, **kwargs):
		user = self.get_argument('user',None)
		favor = self.get_arguments('favor',False)
		# file = self.get_argument('file')
		try:
			file_obj = self.request.files['file']
			for meta in file_obj:
				file_name = meta['filename']
				with open(os.path.join('static','upload',file_name), 'wb') as up:
					up.write(meta['body'])
				IMG_LIST.append(file_name)
		except:
			pass

		self.render('foo/ajax.html', img_list=IMG_LIST)

valid = mod_Validation.ValidateForm()
class ValidateHandler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		self.render('foo/validate.html',ret1='', err1='', ret2='', err2='', ret3='', err3='')

	def post(self, *args, **kwargs):
		# ret1 = valid.fm_valid(self, fm_name='con',fm_type='text', required=False)
		# ret2 = valid.fm_valid(self, fm_name='checkbox',fm_type='checkbox', required=False)
		# ret3 = valid.fm_valid(self, fm_name='file',fm_type='file', required=False)
		# , required = False
		# {'empty':'不能为空','format':'格式错误'}
		# ret1 = valid.fm_valid(self, fm_name='con', fm_type='text',fm_reg=u"^[\u4e00-\u9fa5]+$", err_msg='1111111111111')
		# ret2 = valid.fm_valid(self, fm_name='checkbox', fm_type='checkbox',fm_reg=u"^\w+$", err_msg='22222222222222222')
		# ret3 = valid.fm_valid(self, fm_name='file', fm_type='file',fm_reg=u"^\w+.png", err_msg='333333333333333')

		ret1 = valid.fm_valid(self, fm_name='con', fm_type='text', fm_reg=u"^[\u4e00-\u9fa5]+$", err_msg={'empty':'不能为空','format':'格式错误'})
		ret2 = valid.fm_valid(self, fm_name='checkbox', fm_type='checkbox',fm_reg=u"^\w+$", err_msg={'empty':'不能为空','format':'格式错误'})
		ret3 = valid.fm_valid(self, fm_name='file', fm_type='file',fm_reg=u"^\w+.png", err_msg={'empty':'不能为空','format':'格式错误'})

		# for k in ret1:
		# 	print k,ret1[k]
		#
		# for k in ret2:
		# 	print k,ret2[k]
		#
		for k in ret3:
			print k,ret3[k]

		# print ret1['valid']
		# print ret2['valid']
		print ret3['msg']
		# print ret3['value']

		all = valid.all_valid(ret1['valid'], ret2['valid'], ret3['valid'])
		up = valid.fl_upload(self,'file', all)
		print 'ret_valid：{}'.format(all)
		print 'fl_save--value：{}'.format(up)

		self.render('foo/validate.html', ret1=ret1['value'], err1=ret1['msg'], ret2=ret2['value'], err2=ret2['msg'], ret3=up, err3=ret3['msg'])

class CachePageHandler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		c_time = time.time()
		print self._write_buffer
		self.render('foo/cachepage.html', c_time=c_time)

	def post(self, *args, **kwargs):
		pass